/*
 * Copyright (c) 2002-2006 by OpenSymphony
 * All rights reserved.
 */
package com.nhncorp.usf.core.interceptor.impl.multipart;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.RequestContext;
import org.apache.commons.fileupload.disk.DiskFileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.nhncorp.lucy.common.config.model.ApplicationInfo;

/**
 * Multipart form data request adapter for Jakarta's file upload package.
 *
 * @author Bruce Ritchie
 */
public class JakartaMultiPartRequest extends MultiPartRequest {
    // maps parameter name -> List of FileItem objects
    private final Map<String, List<FileItem>> files = new HashMap<String, List<FileItem>>(2);

    // maps parameter name -> List of param values
    private final Map<String, List<String>> params = new HashMap<String, List<String>>(2);

    // any errors while processing this request
    private final List<String> errors = new ArrayList<String>(1);

    /**
     * Creates a new request wrapper to handle multi-part data using methods adapted from Jason Pell's
     * multipart classes (see class description).
     *
     * @param maxSize        maximum size post allowed
     * @param saveDir        the directory to save off the file
     * @param servletRequest the request containing the multipart
     * @throws java.io.IOException is thrown if encoding fails.
     */
    @SuppressWarnings("unchecked")
	public JakartaMultiPartRequest(HttpServletRequest servletRequest, String saveDir, int maxSize) throws IOException {
        DiskFileItemFactory fac = new DiskFileItemFactory();
        fac.setSizeThreshold(0);

        if (saveDir != null) {
            fac.setRepository(new File(saveDir));
        }

        // Parse the request
        try {
            ServletFileUpload upload = new ServletFileUpload(fac);
            upload.setHeaderEncoding(getHeaderEncoding());
            upload.setSizeMax(maxSize);

            String charset = getPageEncoding();
            List items = upload.parseRequest(createRequestContext(servletRequest));

            for (Object item1 : items) {
                FileItem item = (FileItem)item1;

                if (LOG.isDebugEnabled()) {
                    LOG.debug("Found item " + item.getFieldName());
                }

                if (item.isFormField()) {
                    LOG.debug("Item is a normal form field");
                    List<String> values = params.get(item.getFieldName());

                    if (values == null) {
                        values = new ArrayList<String>();
                        params.put(item.getFieldName(), values);
                    }

                    // bug fix : 기존 ww의 코드는 정상적으로 동작하지 않음
                    if (charset == null) {
                        values.add(item.getString());
                    } else {
                        values.add(item.getString(charset));
                    }
                } else if (item.getSize() == 0) {
                    LOG.warn("Item is a file upload of 0 size, ignoring");
                } else {
                    LOG.debug("Item is a file upload");

                    List<FileItem> values = files.get(item.getFieldName());

                    if (values == null) {
                        values = new ArrayList<FileItem>();
                        files.put(item.getFieldName(), values);
                    }

                    values.add(item);
                }
            }
        } catch (FileUploadException e) {
            LOG.info(e + " (This ERROR will be logged on MultipartInterceptor.)");
            errors.add(e.getMessage());
        }
    }

    /**
     * Gets the page encoding.
     *
     * @return the page encoding
     */
    private String getPageEncoding() {
        return ApplicationInfo.getPageEncoding();
    }

    /**
     * Gets the header encoding.
     *
     * @return the header encoding
     */
    private String getHeaderEncoding() {
        return ApplicationInfo.getPageEncoding();
    }

    /**
     * @see com.nhncorp.usf.core.interceptor.impl.multipart.MultiPartRequest#getFileParameterNames()
     * {@inheritDoc}
     */
    @SuppressWarnings("unchecked")
	public Enumeration getFileParameterNames() {
        return Collections.enumeration(files.keySet());
    }

    /**
     * @see com.nhncorp.usf.core.interceptor.impl.multipart.MultiPartRequest#getContentType(java.lang.String)
     * {@inheritDoc}
     */
    public String[] getContentType(String fieldName) {
        List<FileItem> items = files.get(fieldName);

        if (items == null) {
            return null;
        }

        List<String> contentTypes = new ArrayList<String>(items.size());

        for (FileItem fileItem : items) {
            contentTypes.add(fileItem.getContentType());
        }

        return contentTypes.toArray(new String[contentTypes.size()]);
    }

    /**
     * @see com.nhncorp.usf.core.interceptor.impl.multipart.MultiPartRequest#getFile(java.lang.String)
     * {@inheritDoc}
     */
    public File[] getFile(String fieldName) {
        List<FileItem> items = files.get(fieldName);

        if (items == null) {
            return null;
        }

        List<File> fileList = new ArrayList<File>(items.size());

        for (FileItem fileItem : items) {

            if (!(fileItem instanceof DiskFileItem)) {
                continue;
            }

            fileList.add(((DiskFileItem)fileItem).getStoreLocation());
        }

        return fileList.toArray(new File[fileList.size()]);
    }

    /**
     * @see com.nhncorp.usf.core.interceptor.impl.multipart.MultiPartRequest#getFileNames(java.lang.String)
     * {@inheritDoc}
     */
    public String[] getFileNames(String fieldName) {
        List<FileItem> items = files.get(fieldName);

        if (items == null) {
            return null;
        }

        List<String> fileNames = new ArrayList<String>(items.size());

        for (Object item : items) {
            FileItem fileItem = (FileItem)item;
            fileNames.add(getCanonicalName(fileItem.getName()));
        }

        return fileNames.toArray(new String[fileNames.size()]);
    }

    /**
     * @see com.nhncorp.usf.core.interceptor.impl.multipart.MultiPartRequest#getFilesystemName(java.lang.String)
     * {@inheritDoc}
     */
    public String[] getFilesystemName(String fieldName) {
        List<FileItem> items = files.get(fieldName);

        if (items == null) {
            return null;
        }

        List<String> fileNames = new ArrayList<String>(items.size());

        for (FileItem fileItem : items) {

            if (!(fileItem instanceof DiskFileItem)) {
                continue;
            }

            fileNames.add(((DiskFileItem)fileItem).getStoreLocation().getName());
        }

        return fileNames.toArray(new String[fileNames.size()]);
    }

    /**
     * @see com.nhncorp.usf.core.interceptor.impl.multipart.MultiPartRequest#getParameter(java.lang.String)
     * {@inheritDoc}
     */
    public String getParameter(String name) {
        List<String> list = params.get(name);

        if (list != null && !list.isEmpty()) {
            return list.get(0);
        }

        return null;
    }

    /**
     * @see com.nhncorp.usf.core.interceptor.impl.multipart.MultiPartRequest#getParameterNames()
     * {@inheritDoc}
     */
    @SuppressWarnings("unchecked")
	public Enumeration getParameterNames() {
        return Collections.enumeration(params.keySet());
    }

    /**
     * @see com.nhncorp.usf.core.interceptor.impl.multipart.MultiPartRequest#getParameterValues(java.lang.String)
     * {@inheritDoc}
     */
    public String[] getParameterValues(String name) {
        List<String> list = params.get(name);

        if (list != null && !list.isEmpty()) {
            return list.toArray(new String[list.size()]);
        }

        return null;
    }

    /**
     * @see com.nhncorp.usf.core.interceptor.impl.multipart.MultiPartRequest#getErrors()
     * {@inheritDoc}
     */
    @SuppressWarnings("unchecked")
	public List getErrors() {
        return errors;
    }

    /**
     * Returns the canonical name of the given file.
     *
     * @param filename the given file
     * @return the canonical name of the given file
     */
    private String getCanonicalName(String filename) {
        int forwardSlash = filename.lastIndexOf("/");
        int backwardSlash = filename.lastIndexOf("\\");

        if (forwardSlash != -1 && forwardSlash > backwardSlash) {
            return filename.substring(forwardSlash + 1, filename.length());
        } else if (backwardSlash != -1 && backwardSlash >= forwardSlash) {
            return filename.substring(backwardSlash + 1, filename.length());
        }

        return filename;
    }

    /**
     * Creates a RequestContext needed by Jakarta Commons Upload.
     *
     * @param req the request.
     * @return a new request context.
     */
    private RequestContext createRequestContext(final HttpServletRequest req) {
        return new RequestContext() {

            public String getCharacterEncoding() {
                return req.getCharacterEncoding();
            }

            public String getContentType() {
                return req.getContentType();
            }

            public int getContentLength() {
                return req.getContentLength();
            }

            public InputStream getInputStream() throws IOException {
                return req.getInputStream();
            }

        };
    }
}
